#!/usr/bin/python
from importlib import reload
import os
import argparse
import jinja2

# 解析参数
parser = argparse.ArgumentParser(description='codegen2')
parser.add_argument('--workdir', required=True, help='Work directory name')
parser.add_argument('--model', required=True, help='Model file name relative to workdir')
args = parser.parse_args()

# 设置文件路径
workdir_name = os.path.realpath(args.workdir)
model_filename = os.path.realpath(workdir_name + '/' + args.model)

# 加载一个模板
print("Loading model file: %s" % model_filename)
m = reload.load_source('model', model_filename, )
# 检查模板是否存在
try:
    m.generators
except:
    print("ERROR: The model must define the 'generators' dictionary.")
    exit(1)
# Check if the variable named variables exist
try:
    m.variables
except:
    print("ERROR: The model must define the 'variables' dictionary.")
    exit(1)

# 初始化Jinja2引擎
templateLoader = jinja2.FileSystemLoader(searchpath="/")
templateEnv = jinja2.Environment(loader=templateLoader)

# 主业务逻辑
for template_name in m.generators.keys():
    # 解析文件路径
    template_filename = os.path.realpath(workdir_name + '/' + template_name)
    output_filename = os.path.realpath(workdir_name + '/' + m.generators[template_name])
    # 加载模板
    print(">Loading template file: %s" % template_filename)
    template = templateEnv.get_template(template_filename)
    # 读模板
    print(">>Generating output: %s" % output_filename)
    output_text = template.render(m.variables)
    # 写入文件
    output = open(output_filename, 'w')
    output.write(output_text)
    output.close()

# End of processing

